package com.springboot.frame.starter.intf;

import com.springboot.frame.starter.annotation.SecurityParameter;
import com.springboot.frame.starter.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.HashMap;
import java.util.Map;

/**
 * @author monkey
 * @desc 返回数据加密
 * @date 2018/10/25 20:17
 */
@Slf4j(topic = "response-intf-encode")
@ControllerAdvice
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice {
    @Autowired
    private IntfEncryptionProperties intfEncryptionProperties;

    /**
     * 返回响应接口需要加密的情况
     *
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        SecurityParameter securityParameter = methodParameter.getMethodAnnotation(SecurityParameter.class);
        return methodParameter.hasMethodAnnotation(SecurityParameter.class) && securityParameter.outEncode();
    }

    /**
     * 响应体加密
     *
     * @param body
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Map<String, String> reslutMap = new HashMap<>(1);
        /*try {
            String encryptStr = JsonUtils.toJsonString(body);
            log.info("对方法method :【{}】响应数据进行加密", methodParameter.getMethod().getName());
            String result = AesEncrypt.encrypt(encryptStr, intfEncryptionProperties.getType().getKey(), intfEncryptionProperties.getType().getAes().getOffset());
            reslutMap.put(intfEncryptionProperties.getBodyKey(), result);
            log.info("加密前：【{}】，加密后：【{}】:",encryptStr,result);
            return reslutMap;
        } catch (Exception e) {
            log.error("对方法method :【" + methodParameter.getMethod().getName() + "】响应数据进行加密出现异常：" + e.getMessage());
        }*/
        return body;
    }

}
